<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'

const containerRef = ref<HTMLDivElement | null>(null)
const testRef = ref<HTMLDivElement | null>(null)
let observer: IntersectionObserver
let left: number
onMounted(() => {
  if (containerRef.value) {
    const items = containerRef.value.querySelectorAll('.item')! as NodeListOf<HTMLDivElement>
    // 计算区域viewport with margin root
    left = (containerRef.value.offsetWidth - items[0].offsetWidth) / 2
    // 为了让第一个元素和最后一个元素能够在可见区域
    items[0].style.marginLeft = `${left}px`
    items[items.length - 1].style.marginRight = `${left}px`
    // 初始化,10为gap的值
    containerRef.value.scrollLeft = left + 10

    handleLeftPosition()

    // 每当观察的元素进入区域，或者移动到区域外，都会触发这个回调方法，
    // 并且通过entries能够访问到这个元素
    observer = new IntersectionObserver(
      (entries) => {
        console.log(entries)
        entries.forEach((entry) => {
          // 第二个参数boolean，表示true添加class,false删除class
          entry.target.classList.toggle('focus', entry.isIntersecting)
          if (entry.isIntersecting) {
            console.log('item' + entry.target.textContent + '进入区域')
          } else {
            console.log('item' + entry.target.textContent + '走出区域')
          }
        })
      },
      {
        root: containerRef.value,
        threshold: 0.56,
        rootMargin: `0px -${left}px` // 注意这里是负数，表示根元素的缩小
      }
    )

    items.forEach((item) => observer.observe(item))
  }
})

onUnmounted(() => {
  console.log('取消观察')
  observer.disconnect()
})

function handleLeftPosition() {
  console.log('观察left是否已经计算：', left)
  console.log('当前的scrollLeft=', containerRef.value?.scrollLeft)
  // type guard
  if (containerRef.value && testRef.value) {
    const scrollLeft = containerRef.value.scrollLeft
    //为了方便我定义一下viewport with margin root
    testRef.value.style.left = `${scrollLeft + left}px`
  }
}
</script>

<template>
  <div class="intersection-observer-first-demo__container">
    <h4>处于Viewport with rootmargin中点亮</h4>
    <div ref="containerRef" class="container" @scroll="handleLeftPosition">
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <div class="item">5</div>
      <div ref="testRef" class="root-magin"><code>Viewport with marginRoot</code></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.clip,
.dark-mode {
  .intersection-observer-first-demo__container {
    h4 {
      color: #fff;
    }
    .item {
      background-color: #fff;
    }
  }
}
.intersection-observer-first-demo__container {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .container {
    position: relative;
    margin: 0 auto;
    display: flex;
    gap: 10px;
    max-width: 840px;
    overflow-x: scroll;
  }

  .root-magin {
    position: absolute;
    border: 5px dashed green;
    width: 280px;
    height: 200px;
  }
  .item {
    flex-shrink: 0;
    width: 280px;
    height: 200px;
    background-color: #dcdcdc;
    display: grid;
    place-items: center;

    &.focus {
      background-color: lightblue;
    }
  }
}
</style>
